window.onload = function () {
  var template = `<div class="comment-item">
  <span class="comment-item__avatar">
    <img src="/upload/<%= comment.author.avatar %>" />
  </span>
  <div class="comment-item__content">
    <a class="author" href="/user/<%= comment.author._id %>"><%= comment.author.username %></a
    >
    <div class="comment-item__metadata">
      <span class="date"><%= comment.created %></span>
    </div>
    <div class="comment-item__text"><%- comment.content %></div>

    <% if (authUser && comment.author._id && authUser._id.toString() ===
    comment.author._id.toString()) { %>
    <div class="comment-item__actions">
      <a href="/comment/<%= comment._id %>/remove">删除</a>
    </div>
    <% } %>
  </div>
</div>
`
  var authUser = null;

  function addComment() {
    // 检查是否拿到了 comment__form
    var textarea = document.querySelector('.comment__textarea')
    textarea.innerHTML = null
    // console.log('textarea', textarea);
    if ($('.comment__form').length === 0) return
    $('.comment__form').on('submit', function (e) {
      e.preventDefault()
      $.ajax({
        type: 'get',
        url: '/api/comment',
        data: $(e.target).serialize(),
        success: function (data) {
          console.log(data);
          var html = ejs.render(template, { comment: data, authUser: data.author })
          $('.comment__wrap').prepend(html)

          $('.comment__wrap>p').remove();
        },
        error: function (err) {
          console.log(err);
        }
      })
    })
  }

  addComment()

}
